Skip to content

Add escapeHtml function for HTML context escaping - #1263

Open
pavankumar-vh wants to merge 1 commit into
CodebuffAI:mainfrom
pavankumar-vh:fix/add-escape-html-function
Open

Add escapeHtml function for HTML context escaping#1263
pavankumar-vh wants to merge 1 commit into
CodebuffAI:mainfrom
pavankumar-vh:fix/add-escape-html-function

Conversation

@pavankumar-vh

Copy link
Copy Markdown

Overview

Add a dedicated escapeHtml function for escaping strings in HTML contexts, separate from the existing escapeString function.

Problem

The previous PR (#1231) modified escapeString to escape HTML-unsafe characters, but this could break existing callers that depend on the un-escaped characters passing through (e.g., building strings for JSON parsing or non-HTML contexts).

Fix

Added a separate escapeHtml function that explicitly escapes HTML-unsafe characters (<, >, &, ') to prevent XSS attacks and HTML injection. The existing escapeString function remains unchanged for backward compatibility.

export const escapeHtml = (str: string): string => {
  return JSON.stringify(str)
    .slice(1, -1)
    .replace(/</g, '\\u003c')
    .replace(/>/g, '\\u003e')
    .replace(/&/g, '\\u0026')
    .replace(/'/g, '\\u0027')
}

Testing

Added comprehensive test coverage for both functions:

  • escapeString tests verify it still escapes JSON special characters but NOT HTML-unsafe ones
  • escapeHtml tests verify it properly escapes <script>, &, ', > to prevent XSS
  • Both functions tested with empty strings and regular characters

All 24 tests pass (19 existing + 5 new).

Files Changed

  • common/src/util/string.ts - Added escapeHtml function
  • common/src/util/__tests__/string.test.ts - Added test coverage for both functions

Scope

This change only touches common/ which is an approved contribution area per the Contributing Guide.

The escapeString function is used for generic string escaping (likely for
embedding JS/JSON string literals in generated code), not for HTML output.
Overloading it with HTML escaping would break existing callers that depend
on the un-escaped characters passing through.

Added a separate escapeHtml function that explicitly escapes HTML-unsafe
characters (<, >, &, ') to prevent XSS attacks and HTML injection when
embedding user-controlled strings in HTML contexts.

Also added comprehensive test coverage for both functions to document the
distinction and prevent regressions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant